package analyzer

import (
	"MyWebcrawler/module"
	"errors"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"net/http"
	"path"
	"strings"
)

func GenFunc() []module.ParseResponse {
	parseImg := func(httpResp *http.Response, respDepth uint32) ([]module.Data, []error) {
		dataList := make([]module.Data, 0)
		if httpResp == nil {
			return nil, []error{errors.New("nil httpResp")}
		}
		httpReq := httpResp.Request
		if httpReq == nil {
			return nil, []error{fmt.Errorf("nil HTTP request")}
		}
		reqURL := httpReq.URL
		if httpResp.StatusCode != 200 {
			err := fmt.Errorf("unsupported status code %d (requestURL: %s)", httpResp.StatusCode, reqURL)
			return nil, []error{err}
		}

		body := httpResp.Body
		if body == nil {
			err := fmt.Errorf("nil HTTP response body (requestURL: %s)", reqURL)
			return nil, []error{err}
		}
		var matchedContentType bool
		if httpResp.Header != nil {
			contentTypes := httpResp.Header["Content-Type"]
			for _, ct := range contentTypes {
				if strings.HasPrefix(ct, "text/html") {
					matchedContentType = true
					break
				}
			}
		}
		if !matchedContentType {
			return dataList, nil
		}
		doc, err := goquery.NewDocumentFromReader(body)
		if err != nil {
			return dataList, []error{err}
		}
		errs := make([]error, 0)
		var title string
		doc.Find(".h3.mb-3").Each(func(index int, sel *goquery.Selection) {
			title = sel.Text()
		})

		doc.Find(".panel-body.single.mt-2").Each(func(index int, sel *goquery.Selection) {
			sel.Find("img").Each(func(j int, selection *goquery.Selection) {
				band, ok := selection.Attr("data-src")
				if ok {
					item := make(map[string]interface{})
					imgUrl := band
					item["title"] = title
					item["imgUrl"] = imgUrl
					fileName := path.Base(imgUrl)
					item["fileName"] = fileName
					//fmt.Println(item["title"], "\n", item["imgUrl"], "\n", item["fileName"])
					dataList = append(dataList, module.Item(item))

					//httpReq, err := http.NewRequest("GET", imgUrl, nil)
					//if err != nil {
					//	errs = append(errs, err)
					//} else {
					//	req := module.NewRequest(httpReq, respDepth)
					//	dataList = append(dataList, req)
					//}
				}
			})
		})
		return dataList, errs
	}
	return []module.ParseResponse{parseImg}
}
